package cn.tedu;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 *用户登录(第2版)
 */
public class Demo11 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = scan.nextLine();
        System.out.println("请输入密码:");
        String password = scan.nextLine();
        login(username,password);
    }
    public static void login(String username,String password){
        try(
                Connection conn = DBUtils.getConn()

        ) {
            String sql = "select password from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            //执行查询
            ResultSet rs = ps.executeQuery();
            //判断是否有数据
            if(rs.next()){
                //得到查询到的数据
                String pw = rs.getString(1);
                //那用户密码和查询到的密码比较
                if(pw.equals(password)){
                    System.out.println("登录成功!");
                }else{
                    System.out.println("密码错误!");
                }
            }else {
                System.out.println("用户名不存在!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
